package avicit.bdp.dcs.detail.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.dto.ProcessInstanceDto;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.common.utils.enums.JobType;
import avicit.bdp.dcs.detail.dao.TaskDataDetailDao;
import avicit.bdp.dcs.detail.dto.DataDetailDto;
import avicit.bdp.dcs.detail.dto.TaskDataDetailDTO;
import avicit.bdp.dcs.job.dto.JobDTO;
import avicit.bdp.dcs.job.service.DcsJobService;
import avicit.bdp.dcs.tools.enums.TransferStatus;
import avicit.bdp.dcs.tools.enums.TransferType;
import avicit.bdp.dcs.utils.DcsConstants;
import avicit.bdp.dcs.utils.DcsErrorCode;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.github.pagehelper.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;

/**
 * @金航数码科技有限责任公司
 * @作者：liyb
 * @邮箱：liyb@avic-digital.com
 * @创建时间：2020-08-03 11:32
 * @类说明：
 * @修改记录：
 */
@Service
@Transactional
public class TaskDataDetailService extends BaseService<TaskDataDetailDao, TaskDataDetailDTO> {

    private static final Logger logger = LoggerFactory.getLogger(TaskDataDetailService.class);

    @Autowired
    private TaskDataDetailDao taskDataDetailDao;
    @Autowired
    private DcsJobService jobService;

    /**
     * 获取任务数据明细信息
     * @param jobId
     * @param srcTableName
     * @param currentPage
     * @param pageSize
     * @return
     */
    public QueryRespBean<DataDetailDto> getTaskDataDetailListByJobIdPage(String jobId, String srcTableName, Integer currentPage, Integer pageSize) {
        JobDTO jobDTO = jobService.selectByPrimaryKey(jobId);
        CheckParaUtils.checkDbObjectValidity(jobDTO, logger, String.format(DcsErrorCode.JOB_NULL.getDesc(), jobId));

        ProcessInstanceDto processInstanceDto = jobService.getProcessInstanceByProcessDefinitionId(jobId);

        Page<DataDetailDto> dataDetailList = null;
        if (processInstanceDto == null) {
            // 还未产生流程实例
            com.github.pagehelper.PageHelper.startPage(currentPage, pageSize);
            dataDetailList = taskDataDetailDao.getTaskDataDetailListByJobIdPage(jobId, srcTableName);
        }else{
            com.github.pagehelper.PageHelper.startPage(currentPage, pageSize);
            dataDetailList = taskDataDetailDao.getRunTaskDataDetailListByJobIdPage(jobId, srcTableName);
        }

        DecimalFormat df = new DecimalFormat(DcsConstants.PATTERN);

        if (CollectionUtils.isNotEmpty(dataDetailList)) {
            for(DataDetailDto dataDetailDto : dataDetailList){
                if(dataDetailDto.getEstimateTotal() != null){
                    dataDetailDto.setEstimateTotalString(df.format(dataDetailDto.getEstimateTotal()));
                }
                if(dataDetailDto.getCompletedTotal() != null){
                    dataDetailDto.setCompletedTotalString(df.format(dataDetailDto.getCompletedTotal()));
                }

                if (jobDTO.getJobType() == JobType.SEMISTRUCTURE.getCode()) {
                    dataDetailDto.setSrcTableName(jobService.getSyncFilePath(dataDetailDto.getSrcTableName(), jobDTO.getSelectedFile()));
                }
            }
        }

        QueryRespBean<DataDetailDto> queryRespBean = new QueryRespBean<>();
        queryRespBean.setResult(dataDetailList);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;
    }

    /**
     * 查询数据采集进度
     * @param jobDTO
     * @return
     */
    public String getDataCollectProgressByJobId(JobDTO jobDTO) {
        // 草稿和未启动状态，数据迁移进度为0%
        if(jobDTO.getJobStatus()== TransferStatus.DRAFT.getCode() || jobDTO.getJobStatus()== TransferStatus.NOT_STARTED.getCode()){
            return "0%";
        }

        // 仅仅表结构迁移，数据迁移进度为0%
        if(JobType.TRANSFER.getCode()==jobDTO.getJobType() && TransferType.TABLE.getDescp().equals(jobDTO.getTransferType())){
            return "0%";
        }

        long estimateTotalAll = 0L;
        long completedTotalAll = 0L;
        double progress = 0d;

        DataDetailDto estimateTotal = taskDataDetailDao.getEstimateTotalByJobId(jobDTO.getId());
        if(estimateTotal != null){
            estimateTotalAll = estimateTotal.getEstimateTotal();
        }

        DataDetailDto completedTotal = taskDataDetailDao.getCompletedTotalByJobId(jobDTO.getId());
        if(completedTotal != null){
            completedTotalAll = completedTotal.getCompletedTotal();
        }

        if(estimateTotalAll>0){
            progress = completedTotalAll * 1d / estimateTotalAll;
        }else if(jobDTO.getJobStatus()== TransferStatus.TRANSFERING.getCode() ||
                jobDTO.getJobStatus()== TransferStatus.TRANSFER_FAIL.getCode()){
            // 预估总数为0，迁移中和迁移失败状态，数据迁移进度为0%
            progress = 0;
        }else{
            // 预估总数为0，进度默认100%
            progress = 1;
        }
        return Math.round(progress * 100) + "%";
    }

}
